import type { PluginOption } from "vite";

import path from "path";
import fs from "fs";

import vue from "@vitejs/plugin-vue";
import vueJsx from "@vitejs/plugin-vue-jsx";

import { createHtmlPlugin } from "vite-plugin-html"; // html模板
import createRestartPlugin from "vite-plugin-restart"; // 热更新
import createLegacyPlugin from "@vitejs/plugin-legacy"; // 兼容低版本浏览器，转义JS代码进行兼容
import createBasicSslPlugin from "@vitejs/plugin-basic-ssl"; // 开发时的证书，用于启用 https
import { visualizer as createVisualizerPlugin } from "rollup-plugin-visualizer"; // 可视化打包分析

import AutoImport from "unplugin-auto-import/vite";
import Components from "unplugin-vue-components/vite";
// import { ElementPlusResolver } from "unplugin-vue-components/resolvers";

const resolve = (dir: string) => path.join(__dirname, dir);
function getCurrentVersion() {
  const pkg = fs.readFileSync(resolve("../package.json")).toString();
  return JSON.parse(pkg).version;
}

export function createPlugins(mode: string, envs: Record<string, string>): PluginOption[] {
  const { VITE_PROJECT_TITLE } = envs;
  return [
    createRestartPlugin({
      restart: ["vite.config.ts", ".env", ".env.*", "build/**/*.ts"],
    }),
    vue(), // vue支持
    vueJsx(), // vue-jsx 支持
    AutoImport({
      imports: ["vue", "vue-router", "pinia"],
      dts: resolve("../src/@types/auto-imports.d.ts"), //! 请勿调整，避免识别错误
      eslintrc: {
        enabled: true, // 会在根目录生成 .eslintrc-auto-import.json
        filepath: "eslint-auto-import.json",
      },
    }),
    Components({
      dts: resolve("../src/@types/components.d.ts"),
      // "dirs":["src/components","src/views/"],
      // globs: ["src/components/*.{vue}", "src/views/*.{vue}"],
      collapseSamePrefixes: true,
    }),

    // AutoImport({
    //   resolvers: [ElementPlusResolver()],
    // }),
    // Components({
    //   // resolvers: [ElementPlusResolver({ importStyle: "sass" })],
    //   resolvers: [ElementPlusResolver()],
    // }),
    createBasicSslPlugin({ name: "BiDiao CA", domains: ["localhost", "192.168.30.125", "127.0.0.1"] }), // 证书
    createLegacyPlugin({
      targets: ["> 1%", "chrome >= 68", "last 3 versions", "not ie <= 11", "not dead"],
    }), // 浏览器兼容
    createHtmlPlugin({
      // entry: "../src/main.ts", // 相对于template的路径？？？？
      // template: "public/index.html",
      minify: mode === "production",
      // viteNext: true,
      inject: {
        data: {
          title: VITE_PROJECT_TITLE,
          version: getCurrentVersion(),
        },
      },
    }), // 模版支持 ejs
    createVisualizerPlugin({
      emitFile: true, // 打包后的分析文件会出现在打包好的文件包下
      filename: "stats.html", // 分析图生成的文件名
      open: true, // 如果存在本地服务端口，将在打包后自动展示
      template: "treemap",
      gzipSize: true, // 使用gzip计算大小
      // brotliSize: true, // 使用brotli计算大小
      // sourcemap: true// 使用sourcemap计算大小
    }),
  ];
}
